#!/usr/bin/env python

import numpy as np
import scipy.signal as signal
import wave

freq_min = 10
freq_max = 20
shifting_seconds = 5 # 加速或减速时长
con_seconds = 5 # 匀速时长

SAMPLE_RATE = 4800 # 采样率

def genwave(f0, f1, seconds, phase_diff=90):
    t = np.arange(0, seconds, 1.0/SAMPLE_RATE)
    vleft = signal.chirp(t, f0=f0, f1=f1, t1=seconds, method='linear')
    vright = signal.chirp(t, f0=f0, f1=f1, t1=seconds, method='linear', phi=phase_diff)

    left_scale = vleft * 32000
    right_scale = vright * 32000

    left_data = left_scale.astype(np.int16)
    right_data = right_scale.astype(np.int16)

    cat_data = np.array([left_data, right_data])
    wave_data = np.transpose(cat_data)
    return wave_data

def genaction(f_min, f_max, t_shifting, t_con, is_forward=True):
    phase = 90 if is_forward else -90
    acc = genwave(f_min, f_max, t_shifting, phase)
    con = genwave(f_max, f_max, t_con, phase)
    dec = genwave(f_max, f_min, t_shifting, phase)
    action = np.concatenate((acc, con, dec))
    return action

def genround(f_min, f_max, t_shifting, t_con):
    forward = genaction(f_min, f_max, t_shifting, t_con, True)
    backward = genaction(f_min, f_max, t_shifting, t_con, False)
    return np.concatenate((forward, backward))

# frames = genaction(freq_min, freq_max, shifting_seconds, con_seconds, False)
frames = genround(freq_min, freq_max, shifting_seconds, con_seconds)

seconds = shifting_seconds*2 + con_seconds
fname = "{}~{}Hz-{}s-{}sr.wav".format(freq_min, freq_max, seconds, SAMPLE_RATE)
wf = wave.open(fname, "wb")
wf.setnchannels(2) # 2声道
wf.setsampwidth(2) # 采样宽(字节)
wf.setframerate(SAMPLE_RATE)
wf.setcomptype('NONE','not compressed') # 设置采样格式:无压缩
wf.writeframes(frames.tobytes())
wf.close()
print("generated: {}".format(fname))
